<template>
  <div class="salary">
    <!-- 薪酬头部 -->
    <div class="title">
      <span>薪酬表</span>
    </div>
    <div class="staff-top" @click="returnDetails()">
      <div>
        <a class="return" href="#">
          <img src="../../assets/return.png" />
          返回
        </a>
      </div>
      <h1>员工薪酬明细</h1>
    </div>

    <div class="setupBtn" style="margin: 15px; float: right">
      <div style="margin-left: 15px; float: right">
        <el-input
          placeholder="请输入内容"
          v-model="search"
          class="input-with-select"
        >
          <el-button slot="append" icon="el-icon-search" @click="sousuo">搜索 </el-button>
        </el-input>
      </div>
      <el-button type="primary" plain @click="newAddBtn">新增</el-button>
      <el-button type="primary" plain @click="saveData()">保存</el-button>
      <el-button type="primary" plain @click="copyBtn">复制工资表</el-button>
      <el-button type="primary" plain @click="ImportBtn">导入工资表</el-button>
      <el-button type="primary" plain @click="exportExcel">导出excel</el-button>
    </div>

    <!-- 表格部分 -->
    <el-table
      :data="tableData"
      style="width: 100%"
      show-summary
      :summary-method="getSummaries"
      id="educe-table"
    >

      <el-table-column type="index" label="序号" width="80"> </el-table-column>
      <el-table-column prop="employeeName" label="姓名" width="80">
      </el-table-column>
      <el-table-column prop="cardTypeName" label="证件类型" width="80">
      </el-table-column>
      <el-table-column prop="idCard" label="证件号码" width="180">
      </el-table-column>
      <el-table-column prop="payableSalary" label="工资" width="150">
        <!-- 作用域插槽  row就是用当前行-->
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.payableSalary"
            @input="
              scope.row.payableSalary = checkMoney(scope.row.payableSalary, 11)
            "
            @blur="
              scope.row.payableSalary = changeData(scope.row.payableSalary)
            "
          >
          </el-input>
        </template>
      </el-table-column>
      <el-table-column label="代扣社保">
        <el-table-column prop="endowmentInsurance" label="养老保险" width="120">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.endowmentInsurance"
              @input="
                scope.row.endowmentInsurance = checkMoney(
                  scope.row.endowmentInsurance,
                  10
                )
              "
              @blur="
                scope.row.endowmentInsurance = changeData(
                  scope.row.endowmentInsurance
                )
              "
            >
            </el-input>
          </template>
        </el-table-column>
        <el-table-column prop="medicalInsurance" label="医疗保险" width="120">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.medicalInsurance"
              @input="
                scope.row.medicalInsurance = checkMoney(
                  scope.row.medicalInsurance,
                  10
                )
              "
              @blur="
                scope.row.medicalInsurance = changeData(
                  scope.row.medicalInsurance
                )
              "
            >
            </el-input>
          </template>
        </el-table-column>
        <el-table-column
          prop="unemploymentInsurance"
          label="失业保险"
          width="120"
        >
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.unemploymentInsurance"
              @input="
                scope.row.unemploymentInsurance = checkMoney(
                  scope.row.unemploymentInsurance,
                  10
                )
              "
              @blur="
                scope.row.unemploymentInsurance = changeData(
                  scope.row.unemploymentInsurance
                )
              "
            >
            </el-input>
          </template>
        </el-table-column>
        <el-table-column prop="insuranceCount" label="合计" width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.insuranceCount }}</span>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column prop="housingFund" label="代扣公积金" width="120">
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.housingFund"
            @input="
              scope.row.housingFund = checkMoney(scope.row.housingFund, 10)
            "
            @blur="scope.row.housingFund = changeData(scope.row.housingFund)"
          >
          </el-input>
        </template>
      </el-table-column>
      <el-table-column label="其他扣除">
        <el-table-column prop="annuity" label="企业（职业）年金" width="120">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.annuity"
              @input="scope.row.annuity = checkMoney(scope.row.annuity, 10)"
              @blur="scope.row.annuity = changeData(scope.row.annuity)"
            >
            </el-input>
          </template>
        </el-table-column>
        <el-table-column
          prop="commercialHealthInsurance"
          label="商业健康保险"
          width="120"
        >
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.commercialHealthInsurance"
              @input="
                scope.row.commercialHealthInsurance = checkMoney(
                  scope.row.commercialHealthInsurance,
                  10
                )
              "
              @blur="scope.row.commercialHealthInsurance = changeData()"
            >
            </el-input>
          </template>
        </el-table-column>
        <el-table-column
          prop="taxDeferredEndowmentInsurance"
          label="税延养老保险"
          width="200"
        >
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.taxDeferredEndowmentInsurance"
              @input="
                scope.row.taxDeferredEndowmentInsurance = checkMoney(
                  scope.row.taxDeferredEndowmentInsurance,
                  10
                )
              "
              @blur="
                scope.row.taxDeferredEndowmentInsurance = changeData(
                  scope.row.taxDeferredEndowmentInsurance
                )
              "
            >
            </el-input>
          </template>
        </el-table-column>
        <el-table-column prop="qt" label="其他" width="120">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.qt"
              @input="scope.row.qt = checkMoney(scope.row.qt, 10)"
              @blur="scope.row.qt = changeData(scope.row.qt)"
            >
            </el-input>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column prop="bz" label="备注" width="120">
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.bz"
            @input="scope.row.bz = checkMoney(scope.row.bz, 10)"
            @blur="scope.row.bz = changeData(scope.row.bz)"
          >
          </el-input>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" fixed="right" class="flxed">
        <template slot-scope="scope">
          <span
            style="color: #1e9fff; cursor: pointer"
            @click="deleteRow(scope.row.idCard)"
            >删除</span
          >
        </template>
      </el-table-column>

    </el-table>

    <!-- 新增 弹窗-->
    <el-dialog title="请选择人员" :visible.sync="addStaff">
      <el-table
        :data="addData"
        border
        style="width: 100%"
        @selection-change="handleChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="employeeName" label="姓名" width="120">
        </el-table-column>
        <el-table-column prop="cardTypeName" label="证件类型" width="120">
        </el-table-column>
        <el-table-column prop="idCard" label="证件号码"> </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[10, 20, 30, 40, 50, 60, 70, 80, 90]"
        :page-size="limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="count"
      >
      </el-pagination>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="
            addStaff = false;
            selecTrue();
          "
          >保 存</el-button
        >
        <el-button @click="addStaff = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 复制工资表 -->
    <el-dialog
      title="复制往期工资"
      :visible.sync="dialogVisible"
      width="30%"
      top="25vh"
      :before-close="handleClose"
    >
      <div class="copySalary">
        <div class="block">
          <span class="demonstration"></span>
          <el-date-picker v-model="rq" type="month" placeholder="往期工资">
          </el-date-picker>
        </div>
        <span>复制至</span>
        <span>{{ systemTime }}</span>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 导入工资表 -->
    <el-dialog title="工资导入" :visible.sync="importSalary">
      <div class="importSalary">
        <div class="importRule">
          <span style="color: red">导入规则</span>
          <P>1 支持xls、xlsx的样式的excel表格，暂不支持csv格式</P>
          <P>2 文件大小不能超过10M</P>
        </div>
        <div class="ImportTemplate">
          <div class="box1">
            <img src="../../assets/batch01.png" alt="" />
            <span
              ><el-button type="primary" @click="xiazai"
                >下载导入模板</el-button
              ></span
            >

            <p>下载模板，并按照模板要求格式整理导入信息</p>
          </div>
          <div class="box1">
            <img src="../../assets/batch02.png" alt="" />
            <el-upload
              class="upload-demo"
              action="#"
              ref="upload"
              :file-list="fileList"
              :before-upload="beforeUpload"
            >
              <el-button size="small" type="primary" @click="uploadFiles"
                >点击上传</el-button
              >
            </el-upload>
            <p>下载模板，并按照模板要求格式整理导入支持xls格式文件</p>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '../../utils/request'
import { importBuilding, getToke } from '../../api/table_main'
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
export default {
  name: 'aboout',
  data () {
    return {
      tableData: [], // 数据
      addData: [],
      addStaff: false,
      importSalary: false,
      dialogVisible: false,
      slipId: '',
      limit: 10,
      page: 1,
      count: 0,
      rq: '',
      systemTime: '',
      selectionChange: '',
      // 上传的文件列表
      fileList: [],
      search: ''//input

    }
  },
  created () {
    this.getList()
    this.addDate()
  },
  components: {},
  methods: {

    sousuo(){
      console.log('res');

    },
    addDate () {
      // 日期
      var myDate = new Date() // 获取当前年
      var year = myDate.getFullYear() // 获取当前月
      var month = myDate.getMonth()
      if (month == 0) {
        month = 12
        year = year - 1
      }

      this.systemTime = year + '-' + month
    },

    // 获取地址url
    getUrl () {
      var url = window.location.href
      console.log(url)
      var temp1 = url.split('?')
      var pram = temp1[1]
      var keyValue = pram.split('=')
      this.slipId = keyValue[1]
    },
    // 薪酬明细表
    getList () {
      this.getUrl()
      request
        .get('/salay/getPayrollDetail', {
          params: {
            slipId: this.slipId
          }
        })
        .then((res) => {
          // console.log(res.data)
          if (res.data.code === 0) {
            this.tableData = res.data.data
            this.getSummaries()
            this.countData()
          }
        })
    },
    // 返回
    returnDetails () {
      this.$router.push('/salary')
    },
    // 获取新增按钮表格数据
    getAddList () {
      var ids = ''
      this.tableData.forEach(function (item) {
        if (ids === '') {
          ids = item.employeeId
        } else {
          ids = ids + ',' + item.employeeId
        }
      })
      request
        .post('/employee/queryEmployee', {
          employeeIds: ids,
          limit: this.limit,
          page: this.page
        })
        .then((res) => {
          if (res.data.code === 0) {
            this.addData = res.data.data
            this.count = res.data.count
          }
        })
    },

    // 点击新增关闭
    newAddBtn () {
      this.addStaff = true
      this.getAddList()
    },
    // 新增表格分页 每页条数改变时会触发
    handleSizeChange (val) {
      this.limit = val
      this.page = 1
      this.getAddList()
    },
    // 当前页改变触发
    handleCurrentChange (val) {
      this.page = val
      this.getAddList()
    },
    // 表格新增
    handleChange (row) {
      this.selectionChange = row
      console.log(this.selectionChange)
    },

    // 新增按钮添加数据
    selecTrue () {
      if (this.selectionChange.length > 0) {
        this.selectionChange.forEach((item) => {
          this.tableData.push({
            employeeId: item.employeeId,
            employeeName: item.employeeName,
            cardTypeName: item.cardTypeName,
            idCard: item.idCard,
            payableSalary: '0.00',
            endowmentInsurance: '0.00',
            medicalInsurance: '0.00',
            unemploymentInsurance: '0.00',
            insuranceCount: '0.00',
            housingFund: '0.00',
            annuity: '0.00',
            commercialHealthInsurance: '0.00',
            taxDeferredEndowmentInsurance: '0.00',
            qt: '0.00',
            bz: ''
          })
          this.getAddList()
        })
      }
    },

    // 合计
    getSummaries (param) {
      const { columns, data } = param // 这里可以看出，自定义函数会传入每一列，以及数据
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计'
        } else if (index >= 4) {
          // index>=3后的列进行求和
          // 页面分别统计 处理
          const values = data.map((item) => Number(item[column.property]))
          // 只要你这个数组里面的每一项都不是nan
          if (!values.every((value) => isNaN(value))) {
            // 第一个参数是一个函数，第二个是初始值 而函数里面有两个参数第一次是上次循环中return的值
            // 第一次循环的时候第一个参数为reduce函数的第二个初始值

            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            // 此处结合了方式一的判断处理，实现多种条件处理
            // 此处的column.property获取的值对应<el-table-column>中prop对应的字段
            switch (column.property) {
              case 'total1':
              case 'total2':
              case 'total3':
                return (sums[index] = sums[index])
                break
            }
          } else {
            sums[index] = '' // 如果列的值有一项不是数字，就显示这个自定义内容
          }
        } else {
          sums[index] = ''
        }
      })
      return sums // 最后返回合计行的数据
    },

    // 合计
    countData () {
      this.tableData.forEach(function (item) {
        item.insuranceCount =
          parseFloat(item.endowmentInsurance) +
          parseFloat(item.medicalInsurance) +
          parseFloat(item.unemploymentInsurance)
        item.insuranceCount = item.insuranceCount.toFixed(2)
      })
    },

    // 删除行
    deleteRow (row) {
      this.tableData.forEach((item, index) => {
        if (item.idCard == row) {
          this.tableData.splice(index, 1)
        }
      })
    },
    // 修改值
    changeData (value) {
      if (value === '' || parseFloat(value) === '0') {
        value = '0.00'
      }
      this.countData()
      return value
    },
    // 校验金额
    checkMoney (value, num) {
      if (value !== '' && value != null) {
        value = value.replace(/^0*(0\.|[1-9])/, '$1')
        value = value.replace(/[^\d.]/g, '') // 清除"数字"和"."以外的字符
        value = value.replace(/^\./g, '') // 验证第一个字符是数字而不是字符
        value = value.replace(/\.{1,}/g, '.') // 只保留第一个.清除多余的
        value = value
          .replace('.', '$#$')
          .replace(/\./g, '')
          .replace('$#$', '.')
        value = value.replace(/^(\-)*(\d*)\.(\d\d).*$/, '$1$2.$3') // 只能输入两个小数
        value =
          value.indexOf('.') > 0
            ? value.split('.')[0].substring(0, num) + '.' + value.split('.')[1]
            : value.substring(0, num) // 限制只能输入10/11位整数
      }
      return value
    },
    // 保存
    // 点击保存按钮
    saveData () {
      request.post('/salay/savePayroll', this.tableData).then((res) => {
        console.log(res)
        if (res.data.code == 0) {
          this.slipId = res.data.slipId
          this.getList()
          this.$message({
            message: '保存成功',
            type: 'success'
          })
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },
    // 复制工资表
    copyBtn () {
      this.dialogVisible = true
      request
        .get('/salay/getMonthSalary', {
          params: {
            month: this.month,
            slipId: this.slipId
          }
        })
        .then((res) => {
          console.log(res)
        })
        .then((res) => {
          if (res.data.code == 0) {
            slipId = res.slipId
            this.getList()
          }
        })
    },
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          done()
        })
        .catch((_) => {})
    },

    // 导入工资按钮
    ImportBtn () {
      this.importSalary = true
    },
    xiazai () {
      window.location.href = 'http://localhost:9091/docs/importSalary.xls'
    },
    // //导出excel!!!!!!!!!!!!!!!!!!!!
    exportExcel () {
      request.post('/salay/exportExcel', {}).then((res) => {
        if (res.data.code == 500) {
          this.$message.error(res.data.msg)
        } else {
          window.location.href =
            'http://localhost:9091/docs/importSalary.xls?=' + slipId
        }
      })
    },

    // 上传
    uploadFiles () {
      this.fileList = []
      setTimeout(() => {
        // 清空已上传的文件列表
        this.$refs.upload.clearFiles()
      }, 100)
    },
    beforeUpload (file) {
      // 截取文件后缀名
      const fileName = file.name.substring(file.name.lastIndexOf('.'))
      if (
        fileName.toLowerCase() != '.xls' &&
        fileName.toLowerCase() != '.xlsx'
      ) {
        this.$message.error('文件必须为.xls或xlsx类型')
        this.fileList = []
        return false
      }
      // 读取文件大小 以字节为单位
      var fileSize = file.size
      console.log(fileSize)
      if (fileSize > 1048576) {
        this.uploadShowDialog = false
        this.$message({
          type: 'error',
          showClose: true,
          duration: 3000,
          message: '文件不能大于10M!'
        })
      }
      const formData = new FormData()
      formData.append('file', file)
      importBuilding(formData).then((res) => {
        console.log(res)
        if (res.data.code === 0) {
          this.$message.success('导入成功')
        } else {
          this.$message.error('导入失败')
        }
        return false
      })
    },
    // //文件上传成功时的钩子
    // uploadSuccess(response, file, fileList) {
    //   console.log("上传文件", response.data);
    //   console.log("返回状态", response.code);
    //   console.log(fileList);
    //   if (response.code === 500) {
    //     this.excelData = response.data;
    //     this.exportErrorFile();
    //     return this.$message.error("导入失败！");
    //   } else {
    //     this.isShowFile = true;
    //     return this.$message.success("导入成功！");
    //   }
    // },
    exportExcel () {
      var fix = document.querySelector('.el-table__fixed-right')
      var wb
      // 因为element-ui的表格的fixed属性导致多出一个table，会下载重复内容，这里做一个判断删除掉
      if (fix) {
        wb = XLSX.utils.table_to_book(
          document.querySelector('#educe-table').removeChild(fix),
          { raw: true }
        )
        document.querySelector('#educe-table').appendChild(fix)
      } else {
        // 生成Excel工作簿对象
        wb = XLSX.utils.table_to_book(document.querySelector('#educe-table'), {
          raw: true
        })
      }
      // 获取二进制字符串作为输出
      var wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        book: true,
        type: 'array'
      })
      try {
        FileSaver.saveAs(
          // Blob: 对象表示一个不可变 原始数据的类文件对象,不一定是JS原生格式的数据。
          // File: 基于Blob，继承了blob的功能并将其扩展使其支持用户系统上的文件。
          new Blob([wbout], { type: 'appliction/octet-stream' }),
          // 设置导出的文件名称可随意
          '薪酬明细表.xlsx'
        )
      } catch (e) {
        if (typeof console !== 'undefined') console.log(e, wbout)
      }
      // 返回一个新创建的Blob对象，其内容由参数中给定的数组串联组成。
      return wbout
    }
  }
}
</script>

<style>
.salary {
  margin: 15px 15px;
}
.title span {
  font-size: 18px;
  color: #333;
  border-left: 4px solid #005bac;
  padding-left: 8px;
  line-height: 18px;
}
.staff-top {
  background: #fafafa;
  border-bottom: 1px solid #e4e5e4;
  margin-top: 12px;
  position: relative;
  height: 45px;
  line-height: 45px;
}
.staff-top a.return {
  position: absolute;
  top: 0px;
  left: 12px;
  color: #0088cc;
}
.staff-top a.return img {
  margin-right: 3px;
  display: inline-block;
}
.staff-top h1 {
  text-align: center;
  font-size: 18px;
}
.copySalary {
  display: flex;
  line-height: 40px;
}
.copySalary span {
  margin-left: 5px;
  font-weight: 800;
}
.importSalary {
  width: 550px;
  height: 400px;
  margin: auto;
}
.ImportTemplate {
  display: flex;
  justify-content: space-between;
  width: 550px;
  margin-top: 50px;
  height: 250px;
}
.box1 {
  width: 250px;
  height: 250px;
  display: flex;
  flex-direction: column;
  border: 1px solid #eee;
}
.box1 img {
  display: block;
  width: 50px;
  height: 50px;
  margin: auto;
}
.box1 button {
  width: 150px;
  height: 40px;

  margin-left: 55px;
  margin-bottom: 30px;
}
</style>
